//
//  PerformanceMonitor.swift
//  Mediaplayer
//
//  Created by bin hu on 2025/7/11.
//

import UIKit

// MARK: - 性能监控
protocol PerformanceMonitorDelegate: AnyObject {
    func performanceWarning(category: String, message: String)
}

class PerformanceMonitor {
    private var displayLink: CADisplayLink?
    private var lastTimestamp: CFTimeInterval = 0
    private var frameCount: Int = 0
    private let warningThreshold: Double = 55 // 低于55FPS警告
    private var memoryWarningTimer: Timer?
    
    weak var delegate: PerformanceMonitorDelegate?
    
    func startMonitoring() {
        stopMonitoring()
        
        // 帧率监控
        displayLink = CADisplayLink(target: self, selector: #selector(updateFrameRate))
        displayLink?.add(to: .main, forMode: .common)
        
        // 内存监控
        memoryWarningTimer = Timer.scheduledTimer(
            withTimeInterval: 5,
            repeats: true
        ) { [weak self] _ in
            self?.checkMemoryUsage()
        }
    }
    
    func stopMonitoring() {
        displayLink?.invalidate()
        displayLink = nil
        memoryWarningTimer?.invalidate()
        memoryWarningTimer = nil
    }
    
    @objc private func updateFrameRate(displayLink: CADisplayLink) {
        frameCount += 1
        
        let currentTimestamp = CACurrentMediaTime()
        let elapsed = currentTimestamp - lastTimestamp
        
        // 每秒计算一次帧率
        if elapsed >= 1.0 {
            let fps = Double(frameCount) / elapsed
            
            // 帧率过低警告
            if fps < warningThreshold {
                delegate?.performanceWarning(
                    category: "FrameRate",
                    message: String(format: "Low frame rate: %.1f FPS", fps)
                )
            }
            
            // 重置计数器
            frameCount = 0
            lastTimestamp = currentTimestamp
        }
    }
    
    private func checkMemoryUsage() {
        var taskInfo = task_vm_info_data_t()
        var count = mach_msg_type_number_t(MemoryLayout<task_vm_info>.size) / 4
        
        let result: kern_return_t = withUnsafeMutablePointer(to: &taskInfo) {
            $0.withMemoryRebound(to: integer_t.self, capacity: 1) {
                task_info(mach_task_self_, task_flavor_t(TASK_VM_INFO), $0, &count)
            }
        }
        
        if result == KERN_SUCCESS {
            let usedBytes = taskInfo.phys_footprint
            let usedMB = Double(usedBytes) / 1024 / 1024
            
            // 内存超过400MB警告
            if usedMB > 400 {
                delegate?.performanceWarning(
                    category: "Memory",
                    message: String(format: "High memory usage: %.1f MB", usedMB)
                )
            }
        }
    }
}
